import { createContext, useState, useContext, useCallback, useEffect } from 'react';
import api from '../api/api';
import { useHistory } from 'react-router-dom/cjs/react-router-dom';

const DataContext = createContext({});

export const DataProvider = ({ children }) => {

  const history = useHistory();
  const baseUrl = api.getUri();
  const [keyword, setKeyword] = useState('');
  const [isLoggedIn, setIsLoggedIn] = useState(
    localStorage.getItem('isLoggedIn') === 'true' || false
  );
  const [loginUserId, setLoginUserId] = useState(
    parseInt(localStorage.getItem('loginUserId')) || null
  );

  useEffect(() => {
    if (isLoggedIn) {
      localStorage.setItem('isLoggedIn', isLoggedIn);
    } else {
      localStorage.removeItem('isLoggedIn');
    }
    if (loginUserId) {
      localStorage.setItem('loginUserId', loginUserId);
    } else {
      localStorage.removeItem('loginUserId');
    }
  }, [isLoggedIn, loginUserId]);

  const logout = useCallback(() => {
    localStorage.removeItem('token');
    setIsLoggedIn(false);
    setLoginUserId(null);
    history.push('/login');
  }, [history]);

  return (
    <DataContext.Provider value={{
      baseUrl,
      isLoggedIn,
      setIsLoggedIn,
      loginUserId,
      setLoginUserId,
      keyword,
      setKeyword,
      logout
    }}>
      {children}
    </DataContext.Provider>
  );
};

export default DataContext;
export const useAuth = () => useContext(DataContext);